package com.druid.util;

import com.druid.model.ImageOptions;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class UtilForImage {

    public static void transparentImage(ImageOptions options) throws IOException {
        InputStream inputStream = options.getInputStream();
        OutputStream maskStream = options.getMaskStream();
        OutputStream newImageStream = options.getNewImageStream();
        Rectangle rect = options.getRectangle();

        BufferedImage originalImage = ImageIO.read(inputStream);

        //  绘制mask区域图片
        BufferedImage maskImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D maskG2d = maskImage.createGraphics();
        maskG2d.setColor(new Color(255, 255, 255, 255)); // 透明区域的颜色为白色，不透明区域的颜色为黑色
        maskG2d.fillRect(0, 0, originalImage.getWidth(), originalImage.getHeight());
        maskG2d.setComposite(AlphaComposite.Src);

        //  绘制裁剪mask后的新图
        BufferedImage transparentShape = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D tg2d = transparentShape.createGraphics();
        tg2d.setColor(new Color(0, 0, 0, 0));
        tg2d.fillRect(0, 0, originalImage.getWidth(), originalImage.getHeight());
        tg2d.setComposite(AlphaComposite.Src);
        tg2d.drawImage(originalImage, 0, 0, null); // 先绘制原始图像
        tg2d.setColor(new Color(255, 255, 255, 0)); // 在透明区域绘制白色
        tg2d.fillRect(rect.x, rect.y, rect.width, rect.height);
        tg2d.dispose();

        maskG2d.drawImage(transparentShape, 0, 0, null); // 将透明区域合并到掩模图像中
        maskG2d.dispose();

        // 重新绘制截取区域
        if ( !options.isRectanglePicRelevance() ) {
            Graphics2D og2d = originalImage.createGraphics();
            og2d.setColor(new Color(255, 255, 255, 255));
            og2d.clearRect(rect.x, rect.y, rect.width, rect.height);
            og2d.dispose();
            ImageIO.write(originalImage, "png", newImageStream);
        }else {
            // Save the new image with the transparent area
            ImageIO.write(originalImage, "png", newImageStream);
        }
        // Save the mask image
        ImageIO.write(maskImage, "png", maskStream);
    }
}
